import sas using "${rawsource}\JEI_JEI_2004-2020\jei_2004_2020.sas7bdat", clear
save "${data}\source\JEI_JEI_2004-2020.dta", replace
use "${data}\source\JEI_JEI_2004-2020.dta", clear
	rename *, lower
	reshape long effectifs_moyens_ effectifs_31dec_ assiette_deplaf_ assiette_csg_ cotisation_ cotisation_pp_ cotisation_po_ exo_jei_ exo_jeu_ exo_autres_, i(siren siret) j(year)
	ren *_ *

	destring siren, replace
	merge m:1 siren using "${data}/Utils/SirenZE_liasses.dta", keep(1 3) gen(_mliasseZE)
	ren ZE2010 ZEliasse
	joinby siren year using "${tmp}/SirenZE_engineers_naf", unm(master)
	ren _merge _mDADSshares

	replace ZE2010 = ZEliasse if mi(ZE2010)
	
	rename all_hrs nbheur_tot

*	bys siren ZE2010 year (nbheur_tot): gen apet2 = apet[_N]
*	replace apet2 = ape if mi(apet2)

	bys siren year: gen njeu = (exo_jeu != .)

	bys siren year: egen jeu_firstyear = min((exo_jeu != .)*year)
	replace jeu_firstyear = . if jeu_firstyear == 0

	gen nb_newjeu = njeu*(year==jeu_firstyear)

	collapse (sum) job_eng_hrs nbheur_tot nb_jeu = njeu nb_newjeu (first)  ape (max) jeu_amount = exo_jeu, by(siren ZE2010 year) fast

foreach var of varlist nbheur_tot  job_eng_hrs {
	bys siren year: egen sum_`var' = sum(`var')
	}
gen share = job_eng_hrs / sum_job_eng_hrs
replace share = nbheur_tot / sum_nbheur_tot if mi(share)

sort siren year
bys siren year: egen totshare = sum(share)
su totshare, d
bys siren year: egen nbZE = nvals(ZE2010)
replace share = 1 if mi(share) & totshare == 0 & nbZE == 1

egen exo_tot = rsum(*amount)

foreach var of varlist  nb_jeu {
	gen `var'_split = `var' * share
	}

gcollapse (sum) *_split  nb_jeu nb_newje? je?_amount, by(ZE2010 ape year)


save "${tmp}/JEU_ZE_NAF", replace

